import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/home/Home'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import $XEUtils from 'xe-utils'

Vue.use(VueRouter)

import oneselfCentre from './oneself-centre'
import applicationCenter from './application-center'
import operationsCenter from './operations-center'
import newsCenter from './news-center'
import dataCenter from './data-center'
import developmentCenter from './development-center'
import electronicMap from './electronic-map'
import resourcesCenter from './resources-center'
import someStatements from './some-statements'

const home = [{
  path: '/',
  name: 'Home',
  meta: {
    info: '主页'
  },
  component: Home
}, {
  path: '/login',
  name: 'Login',
  meta: {
    info: '登陆'
  },
  component: () => import("@/views/underlying-support/login")
}, {
  path: '/relogin',
  name: 'reLogin',
  meta: {
    info: '刷新登录'
  },
  component: () => import("@/views/underlying-support/login/RefreshLogin")
}, {
  path: '/1',
  name: 'demo',
  meta: {
    info: '测试'
  },
  component: () => import("@/views/Demo")
}];

let tem = [
  home,
  oneselfCentre,
  applicationCenter,
  operationsCenter,
  newsCenter,
  dataCenter,
  developmentCenter,
  electronicMap,
  resourcesCenter,
  someStatements
]
let routes = $XEUtils.flatten(tem)

//
// 404
routes.push({
  path: '*',
  name: '404',
  meta: {name: '404'},
  component: () => import("@/views/underlying-support/404/404"),
})

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

NProgress.configure({
  easing: 'ease',
  speed: 500,
  showSpinner: false,
  trickleSpeed: 200,
  minimum: 0.3
})

router.beforeEach((t, f, next) => {
  NProgress.start();
  if (!t.query.m) {
    if (t.path === '/') {
      t.query.m = '1';
    } else {
      t.query.m = f.query.m || '0';
    }

    next({
      path: t.path,
      query: t.query
    });
  } else {
    next();
  }
})

router.afterEach((t, f) => {
  NProgress.done();
  if (!t.query['top'] || '0' !== t.query['top']) {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  }
})

const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => {
    NProgress.done();
    return err;
  })
}

const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(to) {
  return VueRouterReplace.call(this, to).catch(err => {
    NProgress.done();
    return err;
  })
}

export default router
